/*
 * Copyright 2013 
 *
 * 
 */

package com.staples.copyprint.webservice.endpoint;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Iterator;

import javax.xml.namespace.QName;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.log4j.Logger;
import org.jdom2.Element;
import org.jdom2.output.XMLOutputter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ws.context.MessageContext;
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;
import org.springframework.ws.server.endpoint.annotation.RequestPayload;
import org.springframework.ws.soap.SoapEnvelope;
import org.springframework.ws.soap.SoapHeader;
import org.springframework.ws.soap.SoapHeaderElement;

import com.staples.copyprint.webservice.service.CallEclService;
import com.staples.copyprint.webservice.service.CreateEfiXmlService;
import com.staples.copyprint.webservice.service.InsufficientConfigurationException;

/**
 * Class Name - CreateSignalEndPoint 
 * This class is the entry point of the
 * Application Getting canonical xml as request and return the same as response
 */
@Endpoint
public class CreateEfiXmlEndPoint {
	private static final String NAMESPACE_URI = "http://schemas.staples.com/esb/createsalesorder/create/V2_0";

	private static final Logger logger = Logger.getLogger(CreateEfiXmlEndPoint.class);

	@Autowired
	private CreateEfiXmlService createEfiXmlService;

	@Autowired
	private CallEclService callEclService;

	/**
	 * @return callEclService
	 */
	public CallEclService getCallEclService() {
		return callEclService;
	}

	/**
	 * @param callEclService
	 *            to set
	 */
	public void setCallEclService(CallEclService callEclService) {
		this.callEclService = callEclService;
	}

	/**
	 * @return the createEfiXmlServic
	 */
	public CreateEfiXmlService getCreateEfiXmlService() {
		return createEfiXmlService;
	}

	/**
	 * @param createEfiXmlService
	 *            the createEfiXmlService to set
	 */
	public void setCreateEfiXmlService(CreateEfiXmlService createEfiXmlService) {
		this.createEfiXmlService = createEfiXmlService;
	}

	/**
	 * Call createEfiXml method of createEfiXmlService interface
	 * 
	 * @param request
	 * @param soapHeader
	 * @throws InsufficientConfigurationException
	 * @throws TransformerException 
	 * @throws IOException 
	 */
	@PayloadRoot(localPart = "CreateSalesOrder", namespace = NAMESPACE_URI )
	public void createEfiXml(@RequestPayload Element request, SoapHeader soapHeader,SoapEnvelope envelope,MessageContext messageContext) throws InsufficientConfigurationException, TransformerException, IOException {

		logger.info("Entering CreateEfiXmlEndPoint.createEfiXml()");
		logger.debug("----->Input Parameter of createEfiXml: " + request);

		
		
		
		DOMSource domSource1 = (DOMSource)envelope.getSource();
		StringWriter writer1 = new StringWriter();
		StreamResult result1 = new StreamResult(writer1);
		TransformerFactory tf1 = TransformerFactory.newInstance();
		Transformer transformer1;

	
			transformer1 = tf1.newTransformer();
			transformer1.transform(domSource1, result1);
			writer1.flush();

			logger.debug("Envelope: " + writer1.toString());


		
		Element doc = null;

		// Read SOAP request header,create EFI xml and call ECL service
		QName headerQ = new QName("http://schemas.staples.com/eai/tid02","SplsTID");
		Iterator<SoapHeaderElement> headerItr = soapHeader.examineHeaderElements(headerQ);
		SoapHeaderElement headerElement = null;
		while (headerItr.hasNext()) {
			headerElement = (SoapHeaderElement) headerItr.next();
			DOMSource domSource = (DOMSource) headerElement.getSource();

			StringWriter writer = new StringWriter();
			StreamResult result = new StreamResult(writer);
			TransformerFactory tf = TransformerFactory.newInstance();
			Transformer transformer;

			try {
				transformer = tf.newTransformer();
				transformer.transform(domSource, result);
			} catch (TransformerException e) {
				logger.error("Exception in CreateEfiXmlEndPoint:", e);
				throw new InsufficientConfigurationException("","Can not create order. \n Reason: " + e.getMessage());
			}
			writer.flush();

			logger.info("Source Value: " + writer.toString());

			String headerName = headerElement.getName().getLocalPart();
			String headerValue = headerElement.getText();
			logger.info("headerName is" + headerName + "element.getName()>>"
					+ headerElement.getName() + "<<Value>>" + headerValue);

		}

		doc = createEfiXmlService.createEfiXml(request);

		logger.info("----->Return value of createEfiXml: " + doc);
		
		
		XMLOutputter printer = new XMLOutputter();
		String efiXML = printer.outputString(doc.getDocument());
		
		
		logger.debug("generated EFI XML >>"+efiXML);
		
		callEclService.pushOrdersToECL(doc, headerElement, request);

		logger.info("Leaving CreateEfiXmlEndPoint.createEfiXml()");

	}

}
